import sqlite3
import argparse
import os

# 定义图像文件扩展名
video_extensions = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv','.mts','.mpeg','.rm', '.webm','.3gp','.mp3','.wav','.f4v','.m4a','.mpg','.rmvb','.vob'}

def get_records_from_video_db(db_path):
    """从给定路径的数据库中提取video_hash表的所有记录"""
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    cur.execute("SELECT file_path, file_name, file_hash FROM video_hash")
    records = cur.fetchall()
    conn.close()
    # 使用file_hash作为键创建字典
    record_dict = {record[2]: record for record in records}  
    return record_dict


def compare_records(base_records, outside_records):
    """
    比较两组记录，找出差异。
    
    返回两个字典：
    - base_unique: 在base_records中有但在outside_records中没有的记录
    - outside_unique: 在outside_records中有但在base_records中没有的记录
    """
    base_unique = {k: v for k, v in base_records.items() if k not in outside_records}
    outside_unique = {k: v for k, v in outside_records.items() if k not in base_records}
    return base_unique, outside_unique

def is_video_file(file_name):
    """判断文件是否是图像文件"""
    # 提取文件扩展名并检查是否在 video_extensions集合中
    ext = os.path.splitext(file_name)[1].lower()
    return ext in video_extensions

def print_records(records, title):
    """打印符合条件的记录"""
    print(f"\n{title}:")
    for hash_val, record in records.items():
        if is_video_file(record[1]):
            print(f"file_path: {record[0]}, file_name: {record[1]}, file_hash: {hash_val}")

def main():
    parser = argparse.ArgumentParser(description="Compare SQLite databases for differences in video_hash tables.")
    parser.add_argument('--base', required=True, help='Path to the base folder containing file_hashes.db')
    parser.add_argument('--outside', required=True, help='Path to the outside folder containing file_hashes.db')
    args = parser.parse_args()

    # 获取两个数据库的完整路径
    base_db_path = os.path.join(args.base, 'file_hash.db')
    outside_db_path = os.path.join(args.outside, 'file_hash.db')

    # 从数据库中获取所有记录
    base_records = get_records_from_video_db(base_db_path)
    outside_records = get_records_from_video_db(outside_db_path)

    # 比较记录
    base_unique, outside_unique = compare_records(base_records, outside_records)

    # 打印结果
    print_records(base_unique, "Records present in base but not in outside")
    print_records(outside_unique, "Records present in outside but not in base")

if __name__ == "__main__":
    main()